
import copy

from coffeetalk.protocol import ioelement

class IONode(ioelement.IOElement):

    def __init__(self, name, attribs, encoded = False):
        
        ioelement.IOElement.__init__(self,name,attribs,encoded)
        
        self.internalnodes = {}
    
    def add(self,newioelement,internal=False):
        """ Add an IONode to this IONode. """
        if not internal:
            self.childelements[newioelement.name] = copy.deepcopy(newioelement)
        else:
            self.internalnodes[newioelement.name] = copy.deepcopy(newioelement)
       
    def remove(self,key,internal=False):
        """ Remove the child CTStream corresponding to key. """
        if internal == True:
            if self.internalnodes.has_key(key):
                del self.internalnodes[key]
        elif self.childelements.has_key(key):
            del self.childelements[key]
            
    def to_string(self, env=None):
        """ Returns a string representaion of this IOStream. 
        
        Keyword arguments:
        level -- How many tabs to be used for output (default 0)
        """      
        returnstring = ''.join(('<i n="',self.encodedname,'"'))
        if len(self.attribs) > 0:
            for key, value in self.encodedattribs.iteritems():
                returnstring = ''.join((returnstring,' ',str(key),'="',str(value),'"'))
        
        if self.internalnodes.has_key('[Access]'):
            access = self.internalnodes['[Access]']
            if access.check_readaccess(env) == False:
                returnstring = ''.join((returnstring,' />'))
                return returnstring        
        nodecount = 0
        for key, value in self.childelements.iteritems():
            if nodecount == 0:
                returnstring = ''.join((returnstring,'>'))
            nodecount = nodecount + 1
            returnstring = ''.join((returnstring,value.to_string(env=env)))    

        if nodecount == 0:
            returnstring = ''.join((returnstring,' />'))
        else:
            returnstring = ''.join((returnstring,'</i>'))
        return returnstring
    
class IOReturnNode(IONode):
    """A stand-in class for creating IONodes to be returned to clients."""
    #TODO: Fix internal node issues. It's all giggity-whacked
    def __init__(self,node):
        
        IONode.__init__(self,node.name,copy.deepcopy(node.attribs),encoded=False)
        if hasattr(node,'internalnodes'):
            if node.internalnodes.has_key('[Access]'):
                self.add(node.internalnodes['[Access]'],internal=True)
        for value in node.childelements.values():
            self.add(IOReturnNode(value))
            
if __name__ == '__main__':
    newnode = IONode('Mike',{})
    copiednode = IOReturnNode(newnode)
    print str(copiednode)
    
        